import { onMounted } from 'vue'

type Options = {
  el: string
}
type Return = {
  imgUrl: string | null
}

// 图片转 换base64
export default function (option: Options): Promise<Return> {
  return new Promise((resolve) => {
    onMounted(() => {
      const img: HTMLImageElement = document.querySelector(option.el) as HTMLImageElement
      img.onload = (): void => {
        resolve({
          imgUrl: base64(img)
        })
      }
    })

    const base64 = (el: HTMLImageElement): string => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
      canvas.width = el.width
      canvas.height = el.height
      ctx.drawImage(el, 0, 0, canvas.width, canvas.height)
      return canvas.toDataURL('image/png')
    }
  })


}